<template>
  <div class="box">
    <div class="btn">
      <a-space>
        <span
          >当前注册功能已<span style="font-weight: bold; color: red">{{
            is_open ? "开启" : "关闭"
          }}</span></span
        >

        <!-- 开启关闭注册功能 -->
        <a-popconfirm
          :title="is_open ? '你确定要关闭？' : '你确定要开启？'"
          ok-text="是"
          cancel-text="否"
          @confirm="confirm"
        >
          <a-button size="large"
            >{{ is_open ? "关闭" : "开启" }}注册功能</a-button
          >
        </a-popconfirm>

        <!-- 新增管理员 -->
        <a-button size="large" @click="openAddForm" type="primary">
          <PlusOutlined />
          新增管理员
        </a-button>
      </a-space>

      <!-- 组件添加管理员弹框 -->
      <add-new-admin
        ref="RefChilde"
        @getData="changePage(paginationProps.current, paginationProps.pageSize)"
      />
    </div>

    <!-- 表格管理员列表 -->
    <a-table
      :columns="columns"
      :data-source="data"
      rowKey="id"
      :pagination="paginationProps"
    >
      <!-- 编辑 -->
      <template #action="{ record }">
        <a-button
          type="primary"
          style="margin-right: 10px"
          @click="goEdit(record.username, record.id, record.name, record.role)"
          >编辑</a-button
        >

        <!-- 删除 -->
        <a-popconfirm
          title="确定要删除该问卷?"
          ok-text="删除"
          cancel-text="取消"
          @confirm="onDelete(record.id)"
        >
          <a-button style="margin-right: 10px">删除</a-button>
        </a-popconfirm>
      </template>
    </a-table>

    <!-- 组件编辑管理员弹框 -->
    <edit-admin
      ref="RefChilde2"
      :chosusername="chosusername"
      :chosId="chosId"
      :chosname="chosname"
      :chosrole="chosrole"
      @getData="changePage(paginationProps.current, paginationProps.pageSize)"
    />
  </div>
</template>
<script lang="ts">
import { PlusOutlined } from "@ant-design/icons-vue";
import { defineComponent, Ref, ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import { get, detele, put } from "../../../utils/request/request";
import AddNewAdmin from "./AddNewAdmin.vue";
import EditAdmin from "./EditAdmin.vue";

// 表格数据
interface DataItem {
  id: number;
  name: string;
  role: number | string;
  username: string;
}

// 分页
interface PaginationProps {
  current: number;
  pageSize: number;
  total: number;
  showSizeChanger: boolean;
  pageSizeOptions: string[];
  showTotal: (total: string) => string;
  onChange: (current: number, pageSize: number) => Promise<void>;
  onShowSizeChange: (current: number, pageSize: number) => Promise<void>;
}

const data: Ref<DataItem[]> = ref([]);

// 表头
const columns = [
  { title: "用户名", dataIndex: "username", align: "center", width: "25%" },
  { title: "姓名", dataIndex: "name", align: "center", width: "25%" },
  { title: "身份", dataIndex: "role", align: "center", width: "20%" },
  {
    title: "操作",
    key: "operation",
    fixed: "right",
    align: "center",
    width: "30%",
    slots: { customRender: "action" },
  },
];

const useAddAmdinEffect = () => {
  const RefChilde = ref();
  const openAddForm = () => {
    RefChilde.value.showDrawer();
  };
  return { RefChilde, openAddForm };
};

const useEditAmdinEffect = () => {
  const RefChilde2 = ref();
  const openEditModal = () => {
    RefChilde2.value.showModal();
  };
  return { RefChilde2, openEditModal };
};


// 调用请求
const useOperationEffect = (
  token: string,
  paginationProps: Ref<PaginationProps>
) => {
  const chosId = ref<number>();
  const chosusername = ref<string>("");
  const chosname = ref<string>("");
  const chosrole = ref<number>();
  const { changePage } = useTableDataEffect(token);
  const { RefChilde2, openEditModal } = useEditAmdinEffect();

  // 删除用户
  const onDelete = async (id: number) => {
    data.value = data.value.filter((item) => item.id !== id);
    const res: any = await detele(`/admin/api/v1/admin/${id}`, {}, token);
    if (res.data.result == 0) {
      changePage(paginationProps.value.current, paginationProps.value.pageSize);
      message.success("删除成功", 3);
    } else {
      message.error("删除失败", 3);
    }
  };
  const goEdit = (username: string, id: number, name: string, role: number) => {
    chosId.value = id;
    chosusername.value = username;
    chosname.value = name;
    chosrole.value = role;
    openEditModal();
  };
  return {
    RefChilde2,
    onDelete,
    goEdit,
    chosId,
    chosusername,
    chosname,
    chosrole,
  };
};

const useTableDataEffect = (token: string) => {
  // 分页配置
  const paginationProps = ref({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    pageSizeOptions: ["5", "10", "15", "20"],
    // showQuickJumper: true,
    showTotal: (total: string) => `共${total}位管理员`,
    onChange: (current: number, pageSize: number) =>
      changePage(current, pageSize),
    onShowSizeChange: (current: number, pageSize: number) =>
      changePage(current, pageSize),
  });
  const changePage = async (pageNumber: number, pageSize: number) => {
    console.log(token)
    const res: any = await get(
      `/admin/api/v1/admin/list?page=${pageNumber}&limit=${pageSize}`,
      token
    );
    const modifiedData = res?.data;
    modifiedData.forEach((account: any) => {
      if (account.role === 1) {
        account.role = "超级管理员";
      } else {
        account.role = "管理员";
      }
    });
    data.value = modifiedData;
  };
  return { paginationProps, changePage };
};

// 关闭注册功能
const useCloseRegister = (token: string) => {
  const is_open = ref<boolean>(true); //注册功能是否关闭，true表示打开的状态，此时显示“关闭”
  const getOpenStatus = async () => {
    const res: any = await get("/admin/api/v1/register/status", token);
    console.log(res);
    if (res?.code === 0) {
      is_open.value = true;
    } else {
      is_open.value = false;
    }
  };
  const putOpenStatus = async () => {
    const res: any = await put(
      "/admin/api/v1/admin/register/status",
      {
        is_open: is_open.value,
      },
      token
    );
    console.log(res);
    if (res.status_code === 0) {
      message.success("更改成功！");
    } else {
      message.error("更改失败！");
    }
  };
  const confirm = async () => {
    is_open.value = !is_open.value; //关闭也就是原来是true =》点击后变成false
    await putOpenStatus();
  };
  return { getOpenStatus, is_open, confirm };
};

export default defineComponent({
  components: {
    PlusOutlined,
    AddNewAdmin,
    EditAdmin,
  },
  setup() {
    const token: string = localStorage.getItem("token") as string;
    const { RefChilde, openAddForm } = useAddAmdinEffect();
    const { paginationProps, changePage } = useTableDataEffect(token);
    const {
      RefChilde2,
      onDelete,
      goEdit,
      chosId,
      chosusername,
      chosname,
      chosrole,
    } = useOperationEffect(token, paginationProps);

    const { getOpenStatus, is_open, confirm } = useCloseRegister(token);

    onMounted(() => {
      changePage(paginationProps.value.current, paginationProps.value.pageSize);
      getOpenStatus();
    });

    return {
      RefChilde,
      openAddForm,
      data,
      columns,
      onDelete,
      goEdit,
      chosId,
      chosusername,
      chosname,
      chosrole,
      paginationProps,
      changePage,
      RefChilde2,
      is_open,
      confirm,
    };
  },
});
</script>

<style lang="less" scoped>
.btn {
  padding-bottom: 15px;
  text-align: right;
}
.box {
  position: relative;
  min-height: 700px;
}
.pagination {
  position: absolute;
  bottom: 0;
  right: 0;
}
</style>
